package com.rainbow.common.core.valid;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 通用验证处理器
 * @author 付为地
 */
@Data
@RequiredArgsConstructor
public class CustomValidator implements ConstraintValidator<NeedCustomValid, String> {

    /**
     * 验证处理类
     */
    private AbstractValidHandler validHandler;

    /**
     * 重写initialize方法获取注解实例
     * @param valid 校验参数
     */
    @Override
    public void initialize(NeedCustomValid valid) {
        if(AbstractValidHandler.class.isAssignableFrom(valid.customHandlerClass())){
            validHandler= (AbstractValidHandler) BeanUtils.instantiateClass(valid.customHandlerClass());
        }else{
            validHandler=new DefaultValidHandler();
        }
        validHandler.setRequired(valid.required());
        if(ObjectUtils.isNotEmpty(valid.initialize())){
            validHandler.setInitialize(valid.initialize());
        }
    }

    /**
     * 验证处理方法
     * @param value 参数值
     * @param context 验证器上下文
     * @return 返回校验结果
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return validHandler.isValid(value,context);
    }

}